import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import User from '@/home/User.vue'
import Shop from '@/home/Shop.vue'
import Detail from '@/home/SellGoodDetail.vue'
import ChatRoom from '@/home/ChatRoom.vue'
import GovBuyBack from '@/home/GovBuyBack.vue'
import ArtiDetail from '@/home/ArtiDetail.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
  },
  {
    path: '/reg',
    name: 'reg',
    component: Register,
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    children: [
      { path: '/home', redirect: 'home/user',},
      
      {
        path: 'user',
        component: User,
      },
      { path: 'library', 
        component: GovBuyBack, 
      }, 
      {
        path: 'shop',
        component: Shop,
      },
      {
        path: 'detail/:id',
        component: Detail,
      },
      {
        path: 'artiDetail/:id',
        component: ArtiDetail,
      },
      {
        path: 'chat',
        component: ChatRoom,
      }
    ]
  },

]

const router = createRouter({
  history: createWebHistory(),
  routes
})
const pathArr = ['shop', 'library', 'chat', 'user']
// 路由守卫
router.beforeEach(async (to, from, next) => {
    // 获取localStorage中的userId
    const token= localStorage.getItem('token') 
  
    // 检查页面是否需要登录权限
    if (!(to.path=="/login" || to.path=="/reg") && !token) {
      // 需要登录权限但未登录，重定向到登录页
      next('/login')
    } else {
      // 否则根据当前路由路径设置导航状态
      for (let i = 0; i < pathArr.length; i++) {
        if (to.path.includes(`/home/${pathArr[i]}`)) {
          // 将导航状态保存到 sessionStorage
          sessionStorage.setItem('navView', i + 1)
          break
        }
      }
      // 不需要登录权限或已登录，正常导航
      next()
    }
})

export default router